<template>
   <div class="app-container">

       <!-- 查询条件 -->
       <el-card>
           <el-form ref="postRef" :inline="true" :model="queryParams" label-width="68px">
               <el-form-item label="用户id" prop="userId">
                   <el-input v-model="queryParams.userId" placeholder="请输入用户id" clearable style="width: 240px" />
               </el-form-item>

               <el-form-item label="用户名" prop="nick_name">
                   <el-input v-model="queryParams.nick_name" placeholder="请输入用户名称" clearable style="width: 240px" />
               </el-form-item>
               <el-form-item label="标题" prop="title">
                   <el-input v-model="queryParams.title" placeholder="请输入内容标题" clearable style="width: 240px" />
               </el-form-item>

              <!-- <el-form-item label="状态" prop="statnick_nameus">
                   <el-select v-model="queryParams.status" placeholder="岗位状态" clearable>
                       <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                           :value="dict.value" />
                   </el-select>
               </el-form-item> -->

               <el-form-item>
                   <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                   <el-button icon="Refresh" @click="resetQuery">重置</el-button>
               </el-form-item>
           </el-form>
       </el-card>

       <!-- 表格 结果展示 -->
       <el-card style="margin-top: 20px;">

           <template #header>
               <el-row :gutter="10">
                   <!-- <el-col :span="1.5">
                       <el-button v-hasPermi="['system:post:add']" type="primary" plain icon="Plus"
                           @click="handleAdd">新增</el-button>
                   </el-col> -->
                   <el-col :span="1.5">
                       <el-button v-hasPermi="['my:content:edit']" type="success" plain icon="Edit" :disabled="single"
                           @click="handleUpdate()">修改</el-button>
                   </el-col>
                   <el-col :span="1.5">
                       <el-button v-hasPermi="['my:content:remove']" type="danger" plain icon="Delete"
                           :disabled="multiple" @click="handleDelete()">删除</el-button>
                   </el-col>
                  <!-- <el-col :span="1.5">
                       <el-button v-hasPermi="['system:post:export']" type="warning" plain icon="Download"
                           @click="handleExport">导出</el-button>
                   </el-col> -->
                   <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
               </el-row>
           </template>

           <el-table v-loading="loading" :data="pageData.rows" style="width: 100%"
               @selectionChange="handleSelectionChange">
               <el-table-column type="selection" align="center" width="55" />
               <el-table-column label="编号" align="center" prop="id" />
               <el-table-column label="发布人" align="center" prop="nickName" :show-overflow-tooltip="true" />
               <el-table-column label="发布人头像" align="center" prop="avatar" :show-overflow-tooltip="true" />
               <el-table-column label="发布标题" align="center" prop="title" :show-overflow-tooltip="true" />
               <el-table-column label="发布内容" align="center" prop="content" :show-overflow-tooltip="true" />
              <el-table-column label="图片" align="center">
                   <template #default="scope">
                     <div v-if="scope.row.src" class="image-container">
                       <img
                         v-for="(item, index) in scope.row.src.split(',')"
                         :key="index"
                         :src="item.trim()"
                         alt="图片"
                         width="150"
                       />
                     </div>
                   </template>
                 </el-table-column>
              <!-- <el-table-column label="状态" align="center" prop="status">
                   <template #default="scope">
                       <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
                   </template>
               </el-table-column> -->
               <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                   <template #default="scope">
                       <span>{{parseTime(scope.row.createTime)}}</span>
                   </template>
               </el-table-column>

               <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                   <template #default="scope">
                       <el-button v-hasPermi="['my:content:edit']" circle type="primary" icon="Edit"
                           @click="handleUpdate(scope.row)" />
                       <el-button v-hasPermi="['my:content:remove']" circle type="danger" icon="Delete"
                           @click="handleDelete(scope.row)" />
                   </template>
               </el-table-column>
           </el-table>
           <pagination  v-model:page="queryParams.pageNum"
               v-model:limit="queryParams.pageSize" :total="pageData.total" @pagination="getList" />
       </el-card>

      <!-- 新增修改对话框 -->
       <el-dialog v-model="open" :title="title" width="500" :close-on-click-modal="false">
           <el-form ref="editRef" :model="form" label-width="80px">
               <el-form-item label="帖子标题" prop="title"
                   :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                   <el-input v-model="form.title" placeholder="请输入帖子标题" />
               </el-form-item>

               <el-form-item label="帖子内容" prop="content"
                   :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                   <el-input v-model="form.content" placeholder="请输入帖子内容" />
               </el-form-item>

               <el-form-item label="图片" prop="src">
                                 <div class="image-list">
                                   <div
                                     v-for="(imageUrl, index) in imageUrls"
                                     :key="index"
                                     class="image-item"
                                   >
                                     <el-image
                                       style="width: 100px; height: 100px; object-fit: cover;"
                                       :src="imageUrl"
                                       @click="handlePicturePreview(imageUrl)"
                                     />
                                    <el-button
                                       style="background-color: red;"
                                       type="text"
                                       icon="el-icon-delete"
                                       size="mini"
                                       @click="handleRemove(index)"
                                     />
                                   </div>

                                   <el-upload
                                     class="avatar-uploader"
                                     :action="uploadUrl"
                                     :show-file-list="false"
                                     name="imgFile"
                                     :data="imageData.ossdata"
                                     :on-success="handleUploadSuccess"
                                     :before-upload="beforeUpload"
                                     accept=".jpeg, .jpg, .png, .gif"
                                   >
                                    <el-icon  class="avatar-uploader-icon"><Plus /></el-icon>
                                   </el-upload>

                                 </div>
                               </el-form-item>

               <!-- <el-form-item label="状态" prop="status"
                   :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                   <el-radio-group v-model="form.status">
                       <el-radio v-for="dict in sys_normal_disable" :key="dict.value"
                           :label="dict.value">{{dict.label}}</el-radio>
                   </el-radio-group>
               </el-form-item> -->
               <!-- <el-form-item label="备注" prop="remark">
                   <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
               </el-form-item> -->
           </el-form>
           <template #footer>
               <div class="dialog-footer">
                   <el-button type="primary" @click="submitForm">确 定</el-button>
                   <el-button @click="cancel">取 消</el-button>
               </div>
           </template>
       </el-dialog>

   </div>


</template>

<script setup name="Series" lang="ts">
     import { ref, reactive, toRefs, getCurrentInstance, ComponentInternalInstance } from 'vue';
     import {appMyPostResp,FormReq,appMyPostReq} from '@/types/app/my'
     import {postConent,updataPostCotent,getpostContent,delContent} from '@/api/app/my/type'
     import type { FormInstance } from 'element-plus';
     import { ElMessage } from 'element-plus';
     // 获取当前vue3的页面this对象转换为proxy代理，查询 sys_dict_data表中的值
     const { proxy } = getCurrentInstance() as ComponentInternalInstance;
     // const { sys_normal_disable } = proxy!.useDict('sys_normal_disable');

    //表单验证对象
    const editRef = ref<FormInstance>()

    //表格选择项
    const mutilSelection = ref<appMyPostResp[]>([])
    //选择项主键
    const ids = ref<number[]>([])

    // 对话框配置
    const open = ref(false);
    const title = ref('');

     //响应式对象
     const loading = ref<boolean>(false)

     // 编辑按钮 默认不启用
     const single = ref<boolean>(true);
     //删除按钮 默认不启用
     const multiple = ref<boolean>(true);
     const showSearch = ref<boolean>(true);

     const imageUrls = ref<string[]>([]); // 用于存储多个图片的 URL


     //自己的定义额外参数
     const imageData = reactive({
         ossdata: {
             fatherPath:'images'
         }
     });

     // 分页数据
     const pageData = reactive<{
         rows : appMyPostResp[]
     }>({
         rows: []
     })

     //响应式代理模型
     const data = reactive<{
         form: FormReq,
         queryParams : appMyPostReq
     }>({
         form:{
             id:undefined,
             title:'',
             content:'',
             src:'',
         },
         queryParams:{
             userId:undefined,
             title:'',
             nick_name:'',
             pageNum: 1,
             pageSize: 10
         }
     })


     // 代理模型转为相应模型
     const { queryParams,form} = toRefs(data)

     // 重置
     function resetQuery() {
         proxy?.resetForm('postRef');
         //查询
         handleQuery();
     }

     // 分页查询
     function getList() {
         loading.value = true;
         console.log(queryParams.value)
         postConent(queryParams.value).then((resp : any) => {
             pageData.rows = resp.data.list;
             loading.value = false;
         });
     }

     function handleSelectionChange(selection: appMyPostResp[]){
         mutilSelection.value = selection
         ids.value = selection.map(row=>row.id)
         //修改按钮禁用值判断
         single.value=selection.length !==1;
         //删除按钮禁用值判断
         multiple.value = selection.length ===0;
     }

     // 查询
     function handleQuery() {
         queryParams.value.pageNum = 1;
         getList();
     }

     //修改
     function handleUpdate(row ?: appMyPostResp){
         let primaryKey : number;
         if(row){
             primaryKey = row.id
         }else{
             primaryKey = ids.value[0]
         }

         reset()

         // 从后台查询值
         getpostContent(primaryKey).then((resp:any)=>{
             form.value=resp.data;
             title.value = '岗位管理--修复';
             if(form.value.src.length>0){
                 imageUrls.value=form.value.src.split(',')
             }
             open.value = true;
         })
     }

     // 删除 或 禁用
     function handleDelete(row ?: appMyPostResp) {
         let primaryKeys : any;
         if (row) {
             primaryKeys = row.id;
         } else {
             primaryKeys = ids.value;
         }

         proxy?.$modal
             .confirm('是否确认删除帖子id为"' + primaryKeys + '"的数据项？')
             .then(function () {
                 return delContent(primaryKeys);
             })
             .then(() => {
                 getList();
                 proxy!.$modal.msgSuccess('删除成功');
             })
             .catch((e : any) => {
                 console.log(e);
             });
     }

     // 新增或修改 对话框取消按钮
     function cancel() {
         open.value = false;
     }

     //修改提交按钮
     async function submitForm(){
         if(!editRef.value){
             return;
         }
         await editRef.value.validate((valid:boolean,fields:any)=>{
             if(valid){
                 //调用修改请求
                 if(form.value.id){
                    form.value.src=imageUrls.value.toString()
                    updataPostCotent(form.value).then(()=>{
                        proxy?.$modal.msgSuccess('修改成功')
                        open.value = false;
                        getList()
                    })
                 }

             }else{
                  console.log('error submit!', fields);
             }
         })

     }

     //重置表单的值
     function reset(){
         form.value={
             id:undefined,
             title:'',
             content:'',
             src:''
         };
         imageUrls.value=[]
         proxy?.resetForm('editRef');
     }
     //初始化查询
     getList()

// ---------------------------------图片



const dialogVisible = ref<boolean>(false); // 对话框可见性
const previewImageUrl = ref<string>(''); // 预览图片 URL
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API+'/oss/uploadImg'); // 替换为你的实际上传 URL

// 处理上传成功
const handleUploadSuccess = (res, file) => {
  imageUrls.value.push(res.data);
  ElMessage.success('上传成功');
};

// 处理图片预览
const handlePicturePreview = (url: string) => {
  previewImageUrl.value = url;
  dialogVisible.value = true;
};

// 处理图片删除
const handleRemove = (index: number) => {
  imageUrls.value.splice(index, 1);
  // ElMessage.success('删除成功');
};

// 在上传之前可以进行的处理，比如验证文件大小等
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    ElMessage.error('上传文件只能是图片!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

</script>

<style>

    .image-list {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
    .image-item {
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .image-item .el-button {
      position: absolute;
      /* top: 0;
      right: 0; */
      /* transform: translate(50%, -50%); */
    }

     .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
</style>
